<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-02 15:03:05
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-06 14:25:47
 -->
<template>
  <div :class="{'app-container': oper !== 'select'}">
    <el-card shadow="never" class="oper-btn-card">
      <div class="clearfix">
        <div class="fl">
          <el-button type="primary" @click="btnAddGood">新增商品</el-button>
          <el-dropdown :show-timeout="60">
            <el-button type="default" @click="btnImport">
              导入<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="out">
                <el-button type="text" style="width:60px;" @click="btnExport">
                  导出
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="fr">
          <div class="clearfix">
            <el-checkbox
              v-model="searchData.isShowDeact"
              true-label="0"
              false-label="1"
              border
            >不显示已停用</el-checkbox>
            <el-input
              v-model="searchData.keywords"
              style="width: 200px"
              placeholder="按编号，名称，规格查询."
              @keydown.enter.native="btnSearch"
            />
            <el-button type="primary" :loading="btnLoading.search" @click="btnSearch">查询</el-button>
            <el-button>筛选</el-button>
          </div>
        </div>
      </div>
    </el-card>
    <el-container>
      <el-aside width="200px" class="aside border-gay">
        <cate-tree @node-click="handleNodeClick" />
      </el-aside>
      <el-main class="noPadding">
        <div>
          <vxe-grid
            ref="table"
            class="grid"
            border
            size="mini"
            resizable
            highlight-hover-row
            show-footer
            :loading="tableLoading.goods"
            :columns="columnsData"
            :data="tableData.goods"
          />
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="pageInfo.rows"
            :page-sizes="[20,30,40]"
            :current-page.sync="pageInfo.page"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>

import {
  updateDeleteStatus,
  updateNewStatus,
  updateRecommendStatus,
  updatePublishStatus
} from '@/api/goods/goods.js'
import { listData, deleteData } from '@/api/goods/goods-sku.js'
import { exportData } from '@/api/goods/goods.js'
import { oftenuse } from '@/libs/mixins'
import { CateTree } from '@/views/bsd/goods/category'
import { getDelButton, getMoreButton, getCopyButton, getUpdateButton } from '@/components/Table/oper-btns.js'
import { srcoll } from './mixins'
import XEUtils from 'xe-utils'
import { exportBlob } from '@/libs/util.js'

const defaultsearchData = { isShowDeact: '0' }

export default {
  name: 'GoodsList',
  components: { CateTree },
  filters: {
    verifyStatusFilter(value) {
      if (value === 1) {
        return '审核通过'
      } else {
        return '未审核'
      }
    }
  },
  mixins: [oftenuse, srcoll],
  props: {
    oper: {
      type: String,
      default: 'list'
    }
  },
  data() {
    return {
      columnsData: [
        { field: 'code', title: '商品编号', showOverflow: true, width: 150 },
        { field: 'name', title: '商品名称/规格', showOverflow: true, width: 200 },
        { field: 'catName', title: '类别', width: 100 },
        { field: 'unitName', title: '基本单位', width: 80, align: 'center' },
        { field: 'price', title: '零售价', showOverflow: true, width: 100,
          slots: {
            default: ({ row, seq }) => {
              const { price } = row
              const priceObj = JSON.parse(price || '{}')
              const value = priceObj['1_1']
              return [<span>{value}</span>]
            }
          }
        }
      ],
      operates: [
        {
          label: '转移到分类',
          value: 'transferCategory'
        },
        {
          label: '移入回收站',
          value: 'recycle'
        }
      ],
      operateType: null,
      searchData: Object.assign({}, defaultsearchData),
      selectProductCateValue: null,
      multipleSelection: [],
      productCateOptions: []
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.$route.params.refresh) {
        vm.getList()
      }
    })
  },
  watch: {
    'searchData.isShowDeact': {
      handler() {
        this.getList()
      }
    },
    selectProductCateValue: function(newValue) {
      if (newValue != null && newValue.length === 2) {
        this.searchData.productCategoryId = newValue[1]
      } else {
        this.searchData.productCategoryId = null
      }
    }
  },
  created() {
    this.handleColumns()
    this.getList()
  },
  methods: {
    btnImport(e) {
      this.$router.push({
        name: 'GoodImport'
      })
    },
    btnExport(e) {
      e.stopPropagation()
      const loading = this.$loading({ fullscreen: false, text: '导出中' })
      exportData('213112').then(res => {
        loading.close()
        let fileName = res.headers['content-disposition'].split('filename=')[1]
        fileName = decodeURI(fileName)
        const data = res.data
        exportBlob(data, fileName)
      })
    },
    btnViewData(row) {
      const { id } = row
      this.$router.push({
        name: 'GoodsSkuView',
        query: { skuid: id }
      })
    },
    btnCopyAddData(row) {
      this.$router.push({
        name: 'GoodCopyAdd',
        query: { skuid: row.id }
      })
    },
    btnUpdateData(row) {
      this.$router.push({
        name: 'GoodsSkuEdit',
        query: { skuid: row.id }
      })
    },
    btnDelData(row) {
      const { id, name } = row
      this.isAllowDel(`确定要删除商品[${name}]吗？`).then(_ => {
        this.delData(id)
      })
    },
    btnSearch() {
      this.pageInfo.current = 1
      this.setBtnLoading('search', true)
      this.getList().then((res) => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('search', false)
      })
    },
    btnSelectData() {
      const tableData = this.getTableData('goods')
      this.$emit('on-goods-select-sure', this.getHasNumGoodsData(tableData))
    },
    jump2goodsDetail(goodsId) {
      if (goodsId) this.$router.push({ name: 'GoodsUpdate', query: { id: goodsId }})
      else this.$router.push({ name: 'GoodAdd' })
    },
    handleColumns() {
      const colMap = {
        'select': this.getSelectOperCols(),
        'list': this.getListOperCols()
      }
      const col = colMap[this.oper]
      this.columnsData.unshift(col)
    },
    getSelectOperCols() {
      return { title: '操作', width: 160, fixed: 'left',
        slots: {
          default: ({ row }) => {
            const data = {
              model: {
                value: row.num,
                callback(value) {
                  XEUtils.set(row, 'num', value)
                }
              },
              props: { size: 'mini' }
            }
            return [
              <el-input-number {...data}></el-input-number>
            ]
          }
        }
      }
    },
    getListOperCols() {
      return { title: '操作', width: 160,
        slots: {
          default: (params) => {
            const { row } = params
            return this.getListOperBtns(row)
          }
        }
      }
    },
    getListOperBtns(row) {
      const h = this.$createElement
      const _this = this
      const moreBtnNode = getMoreButton(h, { on: { click: () => { _this.btnViewData(row) } }})
      const copyAddButton = getCopyButton(h, {
        props: { type: 'default' },
        attrs: { title: '复制并新增' },
        on: { click: () => { _this.btnCopyAddData(row) } }})
      const delBtnNode = getDelButton(h, { on: { click: () => { _this.btnDelData(row) } }})
      const updateBtnNode = getUpdateButton(h, { props: { type: 'primary' },
        on: { click: () => { this.btnUpdateData(row) } }})
      const divNode = h('div', {
        attrs: {
          class: 'table-oper-btns'
        }
      }, [moreBtnNode, copyAddButton, updateBtnNode, delBtnNode])
      return [divNode]
    },
    /**
     * 获取有数量的商品数据
     */
    getHasNumGoodsData(tableData) {
      return tableData.filter(item => { return item.num > 0 })
    },
    // api
    getList(params = { data: this.searchData, page: this.pageInfo }) {
      this.setTableLoading('goods', true)
      return new Promise((resolve, reject) => {
        listData(params).then(res => {
          this.setTableLoading('goods', false)
          if (!res.data.flag) return
          const { records, total } = res.data.data
          records.forEach(item => {
            item.num = 0
          })
          this.setTableData('goods', records)
          this.pageInfo.total = total
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    delData(params) {
      deleteData(params).then(res => {
        if (!res.data.flag) return
        this.getList()
      })
    },
    // on
    handleNodeClick(data) {
      this.$set(this.searchData, 'catId', data.id)
      this.getList()
    },
    btnAddGood() {
      this.jump2goodsDetail()
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: '请选择操作类型',
          type: 'warning',
          duration: 1000
        })
        return
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: '请选择要操作的商品',
          type: 'warning',
          duration: 1000
        })
        return
      }
      this.$confirm('是否要进行该批量操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id)
        }
        switch (this.operateType) {
          case this.operates[0].value:
            this.updatePublishStatus(1, ids)
            break
          case this.operates[1].value:
            this.updatePublishStatus(0, ids)
            break
          case this.operates[2].value:
            this.updateRecommendStatus(1, ids)
            break
          case this.operates[3].value:
            this.updateRecommendStatus(0, ids)
            break
          case this.operates[4].value:
            this.updateNewStatus(1, ids)
            break
          case this.operates[5].value:
            this.updateNewStatus(0, ids)
            break
          case this.operates[6].value:
            break
          case this.operates[7].value:
            this.updateDeleteStatus(1, ids)
            break
          default:
            break
        }
        this.getList()
      })
    },
    handleSizeChange(val) {
      this.pageInfo.current = 1
      this.pageInfo.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageInfo.current = val
      this.getList()
    },
    handleSelectionChange(dataList) {
      this.multipleSelection = dataList
    },
    handleDelete(index, row) {
      this.$confirm('是否要进行删除操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delData(row.id)
      })
    },
    handleShowProduct(index, row) {
      this.jump2goodsDetail(row.id)
    },
    updatePublishStatus(publishStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('publishStatus', publishStatus)
      updatePublishStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateNewStatus(newStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('newStatus', newStatus)
      updateNewStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateRecommendStatus(recommendStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('recommendStatus', recommendStatus)
      updateRecommendStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateDeleteStatus(deleteStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('deleteStatus', deleteStatus)
      updateDeleteStatus(params).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1000
        })
      })
      this.getList()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
